<template>
  <div class="form">
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" label-width="100px" label-position="right">
        <el-form-item style="float: right;">
          <el-button type="primary" v-permission="['suppercontracts.store']" plain @click="add" style="margin:0 30px;">+ New</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <el-table :data="tableData" size="small" stripe border style="width: 100%">
        <el-table-column type="selection" width="50" align="center" />

        <el-table-column label="Title" width="160" align="center">
          <template v-slot="scope">
            <el-link type="primary" @click="edit(scope.row.id)">{{scope.row.title}}</el-link>
          </template>
        </el-table-column>

        <el-table-column label="Start Date" width="200" align="center">
          <template v-slot="scope">
            <span>{{scope.row.startdate}}</span>
          </template>
        </el-table-column>

        <el-table-column label="End Date" width="200" align="center">
          <template v-slot="scope">
            <span>{{scope.row.enddate}}</span>
          </template>
        </el-table-column>

        <el-table-column label="Discount" prop="discount" width="140" align="center">
          <template v-slot="scope">
            <span>{{ scope.row.discount }}% off</span>
          </template>
        </el-table-column>
        <el-table-column label="Status" width="200" align="center">
          <template v-slot="scope">
            <span>{{scope.row.status}}</span>
          </template>
        </el-table-column>

        <el-table-column label="Remarks" width="200" align="center">
          <template v-slot="scope">
            <span>{{scope.row.remarks}}</span>
          </template>
        </el-table-column>



        <el-table-column label="createdTime" min-width="120">
          <template v-slot="scope">
            <span>{{ scope.row.created_at | showDateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="200">
          <template slot-scope="scope">
            <el-button plain v-permission="['suppercontracts.show']" @click="edit(scope.row.id)">View</el-button>
            <el-button plain v-permission="['suppercontracts.destroy']" type="danger" @click="del(scope.row.id)">Expire</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page">
      <el-pagination v-if="isPaginate" background :current-page="page.current_page" :page-sizes="page.sizes"
        :page-size="page.per_page" layout="prev, pager, next" :total="page.total" @size-change="sizeChange"
        @current-change="currentChange" />
    </div>


    <div class="form">

      <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false"
        customClass="customWidth">
        <el-form v-if="dialogFormVisible" ref="ruleForm" :model="formData" :rules="rules" label-width="160px"
          style="width:85%">

          <el-form-item label="Titile" prop="title" style="width:460px">
            <el-input v-model="formData.title" autocomplete="off" placeholder="Titile" />
          </el-form-item>

          <el-form-item label="Start Date" prop="startdate" style="width: 460px;">
            <el-date-picker v-model="formData.startdate" format="MM-dd-yyyy" value-format="MM-dd-yyyy" type="date"
              placeholder="">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="End Date" prop="enddate" style="width: 460px;">
            <el-date-picker v-model="formData.enddate" format="MM-dd-yyyy" value-format="MM-dd-yyyy" type="date"
              placeholder="">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="Discount" prop="discount" style="width: 460px;">
            <el-input-number v-model="formData.discount" :min="1" :max="100" label="Discount"></el-input-number>
          </el-form-item>

          <el-form-item label="Remarks" prop="remarks" style="width: 460px;">
            <el-input v-model="formData.remarks" placeholder="Remark001"></el-input>
          </el-form-item>

          <el-form-item label="Appendix" style="margin-bottom: 0px;">
            <el-upload ref="uploadAvatar" class="avatar-uploader" action="#" :show-file-list="true"
              :on-change="changeAvatar" :auto-upload="false" :http-request="avatarUploadv" name="file" :limit="1">
              <i class="el-icon-upload"> upload files </i>
            </el-upload>
            <ul class="el-upload-list el-upload-list--text" v-if="imageUrl">
              <li tabindex="0" class="el-upload-list__item is-ready">
                <a class="el-upload-list__item-name" :href="imageUrl" target="_blank">
                  <i class="el-icon-document"></i>{{imageUrl}}
                </a>
              </li>
            </ul>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="saveData()">Submit</el-button>
          <el-button @click="dialogFormVisible = false">Cancel</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import CURD from "@/mixin/CURD";
  import {
    index as cclist
  } from "@/api/suppercontract";
  import UploadXls from "@/components/UploadXls";
  import {
    store as uploadImg
  } from "@/api/medias";
  export default {
    name: "contractIndex",
    components: {
      UploadXls: UploadXls
    },
    props: {
      id: {
        type: String,
        default: 0
      }
    },
    mixins: [CURD],
    data() {
      return {
        tableData: [],
        page: {
          total: null,
          per_page: 10,
          sizes: [10, 20, 25, 50],
          current_page: 1
        },
        cid: this.id,
        isEdit: false,
        isNew: false,
        formData: {},
        module: "suppercontract",
        newTitle: "New contract",
        editTitle: "Edit contract",
        isPaginate: true,
        searchForm: {},
        imageUrl: "",
        dialogFormPasswordVisible: false,
        isUploadFile: false,
        importDialogVisible: false,
        fileReader: new FileReader(),
        isShow: false,
        squareUrl: "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png"
      };
    },
    async created() {
      this.searchForm.supper_id = this.cid;
      await this.fetchData();
    },
    methods: {
      saveData() {
        if (this.isUploadFile) {
          this.$refs.uploadAvatar.submit();
        } else {
          this.save("ruleForm");
        }
      },
      async avatarUploadv(options) {
        console.log("avatarUploadv")
        const file = options.file;
        if (file) {
          this.fileReader.readAsDataURL(file);
        }
        this.fileReader.onload = async () => {
          const formData = new FormData();
          formData.append("file", file);
          uploadImg(formData)
            .then((res) => {
              const {
                data
              } = res;
              this.formData.appendix = data.url;
              this.save("ruleForm");
            })
            .catch((err) => {
              options.onError(err);
            });
        };
      },
      changeAvatar(file, fileList) {
        var that = this
        const reader = new window.FileReader();
        reader.readAsDataURL(new Blob([file.raw]));
        reader.onload = (e) => {
          that.formData.appendix = reader.result;
          that.imageUrl = null;
          that.isUploadFile = true;
        };
      },
      async fetchData() {
        this.searchForm.supper_id = this.cid;
        const res = await cclist(
          this.page.current_page,
          this.page.per_page,
          this.searchForm
        );
        if (
          res.data instanceof Object &&
          typeof this.transfromData === "function"
        ) {
          let data = this.transfromData(res.data);
          this.tableData = data;
        } else {
          this.tableData = res.data;
        }
        let {
          rules
        } = require(`@/model/${this.module}`);
        this.rules = rules;
        if (res.meta) {
          // 分页
          res.meta.per_page = parseInt(res.meta.per_page);
          this.page = Object.assign(this.page, res.meta);
        } else {
          this.isPaginate = false; // 不分页
        }
      },
      async add() {
        let {
          Model
        } = require(`@/model/${this.module}`);
        this.formData = new Model();
        this.isNew = true;
        this.isEdit = false;
        this.setTitle();
        this.dialogFormVisible = true;
      },
      setTitle() {
        this.title = this.isNew === true ? this.newTitle : this.editTitle;
        this.cmdTitle = this.isNew === true ? "save" : "modify";
      },
      async save(form) {
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            try {
              this.formData.supper_id = this.cid;
              if (this.isEdit) {
                let {
                  update
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await update(this.formData);
                this.$message.success(info);
              }
              if (this.isNew) {
                let {
                  store
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await store(this.formData);
                this.$message.success(info);
              }
              this.fetchData();
              this.isEdit = false;
              this.isNew = false;
              this.dialogFormVisible = false;
            } catch (error) {
              let result = error.response.data;
              this.$message.error(result.info);
            }
          } else {
            this.$message.error("Data verification error, please input according to the specified rules");
            return false;
          }
        });
      },
      parseErrors(errors) {
        let info = "";
        let name = errors.name;
        if (Array.isArray(name)) {
          name.forEach((item) => {
            info += item + ",";
          });
        }
        info = info.substring(0, str.length - 1);
        return info;
      },
      async edit(id) {
        let {
          show
        } = require(`@/api/${this.module}`);
        let {
          data
        } = await show(id);
        this.formData = data;
        this.imageUrl = this.formData.appendix;
        this.isNew = false;
        this.isEdit = true;
        this.setTitle();
        this.dialogFormVisible = true;
      },
      async del(id) {
        try {
          await this.$confirm("This operation will permanently delete data. Do you want to continue?", "prompt", {
            confirmButtonText: "determine",
            cancelButtonText: "cancel",
            type: "warning"
          });
          let {
            destroy
          } = require(`@/api/${this.module}`);
          let {
            info
          } = await destroy(id);
          this.$message.success(info);
          await this.fetchData();
        } catch (error) {
          this.$message({
            type: "info",
            message: "Cancelled deletion"
          });
        }
      },
      transfromData(data) {
        let result = data.map((item) => {
          item.isEdit = false;
          return item;
        });
        return result;
      }
    }
  }
</script>
<style>
  .customWidth {
    width: 80%;
  }
</style>
<style>
  .warpper {
    padding: 30px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }

  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .green-text {
    color: green;
  }

  .red-text {
    color: red;
  }

  .yellow-text {
    color: yellow;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    line-height: 78px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>